package com.chaoxin.lovehelp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.dao.CategoryDao;
import com.chaoxin.lovehelp.dao.FellowDao;
import com.chaoxin.lovehelp.dao.RecipientDao;
import com.chaoxin.lovehelp.entity.CategoryEntity;
import com.chaoxin.lovehelp.entity.FellowEntity;
import com.chaoxin.lovehelp.entity.RecipientEntity;
import com.chaoxin.lovehelp.common.enums.vo.allNeedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxin.lovehelp.common.utils.PageUtils;

import com.chaoxin.lovehelp.dao.NeedDao;
import com.chaoxin.lovehelp.entity.NeedEntity;
import com.chaoxin.lovehelp.service.NeedService;

import javax.servlet.http.HttpServletRequest;


@Service("needService")
public class NeedServiceImpl extends ServiceImpl<NeedDao, NeedEntity> implements NeedService {

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private FellowDao fellowDao;
    @Autowired
    private RecipientDao recipientDao;


    @Override
    public PageUtils queryPage(HttpServletRequest request, Map<String, Object> params) throws ParseException {
        //获取登录用户
        FellowEntity loginUser = (FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        QueryWrapper<NeedEntity> wrapper = new QueryWrapper<>();
        String recipientName = (String)params.get("recipientName");
        String nurseGrade = (String)params.get("nurseGrade");
        String startCreateTime = (String)params.get("startCreateTime");
        String endCreateTime = (String)params.get("endCreateTime");
        String startAge = (String)params.get("startAge");
        String endAge = (String)params.get("endAge");
        String categoryId = (String)params.get("categoryId");
        String emergencyGrade = (String)params.get("emergencyGrade");
        String isSlove = (String)params.get("isSlove");
        String startSolveTime = (String)params.get("startSolveTime");
        String endSolveTime = (String)params.get("endSolveTime");
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //根据筛选条件获取列表
        wrapper.eq("is_display",1);

        //普通用户只能获取名下受助者的需求
        if (loginUser.getRole()!=1 && loginUser.getRole()!=2){
            wrapper.eq("recipient_id",loginUser.getId());
        }

        if (!StringUtils.isEmpty(emergencyGrade)){
            wrapper.eq("emergency_grade",emergencyGrade);
        }
        if (!StringUtils.isEmpty(isSlove)){
            wrapper.eq("is_slove",isSlove);
        }
        List<NeedEntity> needs = this.list(wrapper);
        if (!StringUtils.isEmpty(startCreateTime)){
            Date date = sdf.parse(startCreateTime);
            needs = needs.stream().filter(vo->!vo.getEstablishTime().before(date)).collect(Collectors.toList());
        }
        if (!StringUtils.isEmpty(endCreateTime)){
            Date date = sdf.parse(endCreateTime);
            needs = needs.stream().filter(vo->!vo.getEstablishTime().after(date)).collect(Collectors.toList());
        }
        if (!StringUtils.isEmpty(startSolveTime)){
            Date date = sdf.parse(startSolveTime);
            needs = needs.stream().filter(vo->!vo.getSolveTime().before(date)).collect(Collectors.toList());
        }
        if (!StringUtils.isEmpty(endSolveTime)){
            Date date = sdf.parse(endSolveTime);
            needs = needs.stream().filter(vo->!vo.getSolveTime().after(date)).collect(Collectors.toList());

        }
        List<allNeedVo> vos = new ArrayList<>();
        for (int i = 0; i < needs.size(); i++) {
            allNeedVo vo = new allNeedVo();
            BeanUtils.copyProperties(needs.get(i),vo);
            RecipientEntity recipient = recipientDao.selectById(vo.getRecipientId());

            if (!StringUtils.isEmpty(recipientName)){
                if(recipient.getName().indexOf(recipientName)<0){
                    continue;
                }
            }
            if (!StringUtils.isEmpty(categoryId)){
                System.out.println(categoryId);
                if(recipient.getCategoryId()!=Integer.parseInt(categoryId)){
                    continue;
                }
            }
            if(!StringUtils.isEmpty(nurseGrade)){
                if(recipient.getNurseGrade()!=Integer.parseInt(nurseGrade)){
                    continue;
                }
            }
            if(!StringUtils.isEmpty(startAge)){
                if(recipient.getAge()<Integer.parseInt(startAge)){
                    continue;
                }
            }
            if (!StringUtils.isEmpty(endAge)){
                if(recipient.getAge()>Integer.parseInt(endAge)){
                    continue;
                }
            }
            vo.setRecipientName(recipient.getName());
            vo.setAge(recipient.getAge());
            vo.setNurseGrade(recipient.getNurseGrade());
            vo.setGender(recipient.getGender());
            vo.setCategoryId(recipient.getCategoryId());

            CategoryEntity category = categoryDao.selectById(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            if(recipient.getFellowId()!=null){
                FellowEntity fellow = fellowDao.selectById(recipient.getFellowId());
                vo.setFellowId(fellow.getId());
                vo.setFellowTel(fellow.getTel());
                vo.setFellowName(fellow.getName());
            }
            vos.add(vo);
        }


        //分页处理
        Integer pageIndex = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        int from = (pageIndex - 1) * limit;
        int to = from + limit > vos.size() ? vos.size() : from + limit;
        List<allNeedVo> vos1 = new ArrayList<>(vos.subList(from, to));
        IPage<allNeedVo> page = new Page<>(pageIndex, limit);
        page.setRecords(vos1);
        page.setTotal(vos.size());
        page.setPages(vos.size() % limit > 0 ? vos.size() / limit + 1 : vos.size() / limit);
        return new PageUtils(page);
    }

    @Override
    public void removeIds(List<Integer> list) {
        if(list!=null){
            for (Integer id: list) {
                NeedEntity need = this.baseMapper.selectById(id);
                need.setIsDisplay(0);
                this.baseMapper.updateById(need);
            }
        }
    }

    //获取某个需求详情
    @Override
    public allNeedVo getNeedVo(Integer id) {
        NeedEntity need = this.getById(id);
        allNeedVo vo = new allNeedVo();
        BeanUtils.copyProperties(need,vo);
        RecipientEntity recipient = recipientDao.selectById(vo.getRecipientId());
        vo.setRecipientName(recipient.getName());
        vo.setGender(recipient.getGender());
        vo.setAge(recipient.getAge());

        if(recipient.getFellowId()!=null){
            FellowEntity fellow = fellowDao.selectById(recipient.getFellowId());
            vo.setFellowId(fellow.getId());
            vo.setFellowName(fellow.getName());
            vo.setFellowTel(fellow.getTel());
        }
        return vo;
    }


}